// 商品列表的当前页面和对应显示的文本
var productCurrentPage = 1;
var noMoreProductText = "<div class='noMoreProduct'></div>";
var getMoreProductText = "<div class='getMoreProduct'></div>";

// 订单列表的当前页面和对应显示的文本
var orderCurrentPage = 1;
var noMoreOrderText = "<div class='noMoreOrder'></div>";
var getMoreOrderText = "<div class='getMoreOrder'></div>";

// 确认收货的订单号
var confirmOrderNo = "";
/*
	商城首页 加载商品列表
 */
function drawProductList(productPage) {
	var data = {
		pageNum: productPage,
		pageSize: 10
	};
	console.log(data);
	$(".loading").show();
	$.ajax({
		url: $.httpRootPath()+'rest/notice/getListByMem',
		type: 'GET',
		dataType: 'json',
		data: data,
		cache: false,
		timeout: 15000,
		success: function(r) {
			console.log(r);

			$(".loading").hide();
			$(".product_list .noMoreProduct,.product_list .getMoreProduct").remove();
            window.location.href ="wxmp/info/noGroup"
			if (r.code != "00") {
				$(".product_list").append(noMoreProductText);

				return;
			}

			for (var i = 0; i < r.data.length; i++) {
				var notice = r.data[i];
                notice.picture = "img/6d91849a-2718-4854-8b2d-3100adf66b14.png"

				var p = "<div class='product_wrap' onclick='goToProductDetail(" + notice.id + ")'>";
				p += "<img src='" + notice.picture + "'>";
				p += "<p>";
				p += "【" + notice.title + "】";
				p += "<span>" + notice.count + "</span>";
				p += "</p>";
				p += "</div>";
				$(".product_list").append(p);
			}

			// 有下一页 显示加载更多的按钮
			if (r.pager.hasNextPage) {
				$(".product_list").append(getMoreProductText);
				productCurrentPage++;
			} else {
				$(".product_list").append(noMoreProductText);

			}

		},
		error: function(e) {
			$(".loading").hide();
			ajaxErrorEvent(e);

		}
	});


}

/*
	跳转到商品详情
 */
function goToProductDetail(id) {
	var url = window.location.href = 'wxmp/info/notice?id=' + id;
	window.location.href = url;

}
function gotoFollowPage() {
    window.location.href = "wxmp/yellow/toFollowList";
}
function gotoDriverAddPage() {
    window.location.href = "wxmp/driver/driver/edit";
}
function gotoVehicleAddPage() {
    window.location.href = "wxmp/driver/vehicle/edit";
}
function gotoBirthdayRemindAddPage() {
    window.location.href = "wxmp/remind/birthday/edit";
}
/*
	跳转到订单列表
 */
function goToOrderList() {
	// window.location.href = 'mall_order_list.html';
	// window.location.href = 'prod/btOrder/toListPage';

}
function goToGroupList() {
    // window.location.href = 'mall_order_list.html';
    window.location.href = 'wxmp/yellow/group?fromPage=yellowPage';

}

function goToList(id) {
	// window.location.href = "mall_order.html?id=" + id;
	// window.location.href = "prod/toListPage";
}
/*
	加载商品详情
 */
function drawProductDetail(r) {
	var res = r.object;
	if (res.deleted == 1) {
		$(".wrap").addClass('none');
		$(".mall_nodata").removeClass('none');
		return;
	}
	var picArray = res.picture.replace(/\s/, '').split(";");
	var detailArray = res.description.replace(/ /, '').split(";");
	$("#price").html((res.price / 100).toFixed(2)); // 原价
	$("#orgPrice").html((res.orgPrice / 100).toFixed(2)); //  现价
	$("#detaiTitle").html("[" + res.issuer + "]" + res.name); //  标题
	// 轮播图
	for (var i = 0; i < picArray.length; i++) {
		var p2 = "<li class='hiSlider-item'>";
		p2 += "<img src='" + picArray[i] + "'></li>";
		$("#detailPicSlider").append(p2);
	}
	// 详情图
	for (var j = 0; j < detailArray.length; j++) {
		var p3 = "<img src='" + detailArray[j] + "'>";
		$("#productDetail").append(p3);
	}

}


/*
	跳转到下单页面
 */
function goToOrder(id) {
	// window.location.href = "mall_order.html?id=" + id;
	window.location.href = "prod/toBuyProductPage?id=" + id;
}

/*
	下单页面 加载商品信息
 */
function drawOrderProduct(res) {
	if (res.code != "00") {
		alert_LHX({
			hasBtn: 0,
			msg: "未获取到信息，请退出再重新进入页面！"
		});
		return;
	}
	var info = res.object;
	var picArray = info.picture.replace(/\s/, '').split(";");
	lastUpDateTime = info.lastUpDateTime;
	$("#orderProductPic").attr("src", picArray[0]);
	$("#orderProductTitle").html("【" + info.issuer + "】" + info.name);
	$("#orderProducPrice").html((info.price / 100).toFixed(2));
}


/*
	下单页面 加载地址信息
 */
function drawOrderAdress(res) {
	if (res.respCode != "00") {
		$(".noaddress").removeClass('none');
		$(".has_address ").addClass('none');
		return;
	}
	var info = res.object;
	$("#address_name").html(info.deliveryName);
	$("#address_tel").attr("data-tel", info.deliveryPhone).html(info.deliveryPhone.substring(0, 3) + "****" + info.deliveryPhone.substring(info.deliveryPhone.length - 4));
	$("#address_address").html(info.province + " " + info.city + " "  + info.district + " " + info.detailAddr);
	$("#enterArea").html(info.province + " " + info.city + " " + info.district);
	$("#enterAddress").val(info.detailAddr);
	$(".area_text").addClass('hasSelect');
}

/*
	保存地址
 */
function saveAddress(name, tel, pro, city, dist, detail, callback) {
	var data = {
		deliveryName: name,
		deliveryPhone: tel,
		province: pro,
		city: city,
		district: dist,
		detailAddr: detail
	};
	console.log(data);
	$(".loading").show();
	$.ajax({
		url: 'prod/saveAddr',
		// url: $.testRootPath() + '/prod/saveAddr',
		type: 'POST',
		dataType: 'json',
		data: data,
		cache: false,
		timeout: 15000,
		success: function(r) {
			console.log(r);
			$(".loading").hide();

			if (r.respCode != "00") {
				$(".tips-error").html(r.msg).removeClass('none');
				return false;
			}
			$(".tips-error").addClass('none');
			if (callback && typeof(callback) == "function") {
				callback();
			}

		},
		error: function(e) {
			$(".loading").hide();
			if (e.statusText == "timeout" || window.navigator.onLine == false) {
				$(".tips-error").html("网络异常，请稍后重试").removeClass('none');
				return false;
			}
			$(".tips-error").html("服务器异常，请稍后重试！").removeClass('none');

		}
	});
}

/*
	提交订单并发起支付
 */
function submitOrder(id, name, address, tel, lastUpDateTime) {

	var data = {
		id: id,
		/*提测后修改*/
		// deliveryName: name,
		// deliveryAddr: address,
		// deliveryPhone: tel,
        deliveryName: "",
        deliveryAddr: "",
        deliveryPhone: "",
		lastUpDateTime: lastUpDateTime

	};

	console.log(data);
	// signature start --
	var time = (new Date()).valueOf();
	var sig_param = data;
	sig_param.time = time;
	sig_param.token = token;
	data.sig = reckonSig(sig_param);
	// -- signature end

	$(".loading").show();
	$.ajax({
		// url: $.testRootPath() + '/prod/btOrder/create',
		url: 'prod/btOrder/create/' + time,
		type: 'POST',
		dataType: 'json',
		data: data,
		cache: false,
		timeout: 15000,
		success: function(r) {
			console.log(r);
			//alert(JSON.stringify(r));
			$(".loading").hide();

			if (r.respCode != "00") {
				errorToast(r.msg, 3);
				return false;
			}

			// signature validatiton start --
			//判断sig, 验证签名
			if (!r.sig) {
				alert_LHX({
					hasBtn: 1,
					msg: '验证错误'
				});
				return;
			}

			var return_sig = r.sig;
			delete r.sig;
			var default_data = {
				token: token
			};
			var sig = reckonSigGet(default_data, r);
			if (return_sig != sig) {
				alert_LHX({
					hasBtn: 1,
					msg: '验签失败'
				});
				return;
			}
			// -- signature validatiton end

			var orderNo = r.orderNo;
			wx.chooseWXPay({
				timestamp: r.timeStamp, // 支付签名时间戳
				nonceStr: r.nonceStr, // 支付签名随机串，不长于 32 位
				package: r.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
				signType: r.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
				paySign: r.paySign, // 支付签名
				// appId: r.appId,
				success: function(res) {
					//alert("支付成功");
					orderConfirm(orderNo);
				},
				cancel: function() {
					// 用户取消支付后执行的回调函数
					//alert("支付取消");
				},
				fail: function() {
					// 用户取消支付后执行的回调函数
					//alert("支付失败");
					alert_LHX({
						hasBtn: 1,
						msg: "系统异常，支付失败，请重试！"
					});

				},
			});


		},
		error: function(e) {
			$(".loading").hide();
			ajaxErrorEvent(e);

		}
	});
}

/*
	通知后台支付成功
 */
function orderConfirm(orderNo) {
	$(".loading").show();
	var data = {
		orderNo: orderNo
	};

	// signature start --
	var time = (new Date()).valueOf();
	var sig_param = data;
	sig_param.time = time;
	sig_param.token = token;
	data.sig = reckonSig(sig_param);
	// -- signature end

	$.ajax({
		// url: $.testRootPath() + '/prod/checkTransNotice',
		url: 'prod/checkTransNotice/' + time,
		type: 'POST',
		dataType: 'json',
		data: data,
		cache: false,
		timeout: 10000,
		complete: function(r) {
			//alert("confirm sent");
			//alert("订单状态:"+r);
			$(".loading").hide();
			if (r.respCode == "00") {								
				// signature validatiton start --
				//判断sig, 验证签名
				if (!r.sig) {
					alert_LHX({
						hasBtn: 1,
						msg: '验证错误',
						clickEvent: function () {
							window.location.href="prod/btOrder/toListPage";
						}
					});
					return;
				}

				var return_sig = r.sig;
				delete r.sig;
				var default_data = {
					token: token
				};
				var sig = reckonSigGet(default_data, r);
				if (return_sig != sig) {
					alert_LHX({
						hasBtn: 1,
						msg: '验签失败',
						clickEvent: function () {
							window.location.href="prod/btOrder/toListPage";
						}
					});
					return;
				}
				// -- signature validatiton end
			
			}
			window.location.href = "prod/buySuccess?orderNo=" + orderNo;

		}
	});
}

/*
	获取订单列表
 */
function getOrderList(productPage) {
	console.log('step into getOrderList()');
    var data = {
        usePager:"true",
        pageNum: productPage,
        pageSize: 10
    };
	$(".loading").show();
	$.ajax({
		// url: $.testRootPath() + '/prod/btOrder/list',
		url: $.httpRootPath()+'rest/notice/getListByMem',
		type: 'GET',
		dataType: 'json',
		data: data,
		cache: false,
		timeout: 20000,
		success: function(r) {
			console.log(r);
			$(".loading").hide();
			$(".order-list .noMoreOrder,.order-list .getMoreOrder").remove();

			if (r.code != "00") {
				if ($(".order-list").children().length == 0) {
					$(".noorder").removeClass('none');
					$(".wrap").addClass('none');
					return;
				}
				$(".order-list").append(noMoreProductText);
				errorToast(r.msg, 3);
				return;
			}
			if ( r.data.length == 0){
                $(".noorder").removeClass('none');
                $(".wrap").addClass('none');
                return;
			}
			for (var i = 0; i < r.data.length; i++) {
				var info = r.data[i];
				var  picture ='img/nodata.png';
				if (typeof(info.picture) != 'undefined' && info.picture != ""){
					picture = info.picture;
				}
				var payTime = info.createTime.substring(0,10);
				var title = info.title ;
				var p = "<div class='order-item' id='" + info.count + "'><h3 class='list_title'>";
				// 订单信息部分
				p += "【" + info.orgName+"】"+ "<i>" + payTime + "</i></h3>";
				p += "<div class='order_detail list_detail' onclick='goToProductDetail("+info.id+")'>";
				p += "<img src='" + picture + "'>";
				p += "<p><i>" + title + "</i></p>";
				p += "<span>" + (+info.count) + "</span></div>";
				// 联系人信息部分
				// p += "<div class='list_address'><h3>";
				// p += "<span class='orderlist_name'>" + "XXXX" + "</span>";
				// p += "<span class='orderlist_tel'>" +"XXXX"+ "</span></h3>";
				// p += "<p><span class='orderlist_addr'>" + "XXXX" + "</span></p></div></div>";
				// end

				$(".order-list").append(p);

				// render logistics start
				var p2 = "<div class='process'>";
				p2 += "<p class='process_a clr_blue'>";
				p2 += "<i class='iconfont icon-qian'></i>已支付</p>";

				// 待发货
				if (false) {
					p2 += "<p class='process_b-1'>";
					p2 += "<i class='iconfont icon-fahuo'></i>待发货</p>";
				}

				// 已发货
				if (false) {
					p2 += "<p class='process_b-2'>";
					p2 += "<i class='iconfont icon-fahuo'></i>已发货（<span>";
					p2 += info.expressCmpy + " <b class='clr_blue'>" + info.courierNumber + "</b></span>）</p>";
					p2 += "<div class='deliveryBtn_wrap'>";
					p2 += "<div class='deliveryBtn' onclick='askWhetherConfirm(\"" + info.orderNo + "\")'>确认收货</div></div>";
				}
				// 已收货
				if (false) {
					p2 += "<p class='process_b-2 clr_blue'>";
					p2 += "<i class='iconfont icon-fahuo'></i>已发货（<span>";
					p2 += info.expressCmpy + " <b class='clr_blue'>" + info.courierNumber + "</b></span>）</p>";
					p2 += "<p class='process_c clr_blue'>";
					p2 += "<i class='iconfont icon-queren'></i>已确认收货</p>";
				}
				// end
				$("#" + info.orderNo).append(p2);
			}

			// 有下一页 显示加载更多的按钮
			if (r.pager.hasNextPage) {
				$(".order-list").append(getMoreOrderText);
				orderCurrentPage++;
			} else {
				$(".order-list").append(noMoreOrderText);

			}

		},
		error: function(e) {
			$(".loading").hide();

			// 列表为空时 切换到无订单界面
			if ($(".order-list").children().length == 0) {
				$(".noorder").removeClass('none');
				$(".wrap").addClass('none');
				return;
			}
			// 列表不为空 弹出toast
			ajaxErrorEvent(e);
		}
	});
}

/*
	弹出提示框询问是否确认收货
 */
function askWhetherConfirm(orderNo) {
	confirmOrderNo = orderNo;
	alert_LHX({
		hasBtn: 2,
		msg: "是否确定收货？",
		clickEvent: function () {
			$(".mask_layer, .mask_layer > div").addClass('none');
			confirmReceipt(confirmOrderNo);
		}

	});
}

/*
	确认收货
 */
function confirmReceipt(orderNo) {
	console.log('step into confirmReceipt()');
	if (!orderNo) { return; }
	var data = {
		orderNo: orderNo
	};

	$(".loading").show();
	$.ajax({
		// url: $.testRootPath() + '/prod/btOrder/confirm',
		url: 'prod/btOrder/confirm',
		type: 'POST',
		dataType: 'json',
		data: data,
		cache: false,
		timeout: 20000,
		success: function(r) {
			$(".loading").hide();

			// 确认成功 移除收货按钮
			$("#" + orderNo + " .deliveryBtn_wrap").remove();
			$("#" + orderNo + " .process_b-2").addClass('clr_blue');
			$("#" + orderNo + " .process").append("<p class='process_c clr_blue'><i class='iconfont icon-queren'></i>已确认收货</p>");

		},
		error: function(e) {
			$(".loading").hide();
			ajaxErrorEvent(e);
		}

	});
}